import { PlusOutlined } from '@ant-design/icons';
import ProForm from '@ant-design/pro-form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, Drawer, Form, Input, message, Modal, Popover, Tag } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import AccountDetail from './components/AccountDetail';
import AddFrom from './components/AddForm';
import type { AddItem, TableListItem } from './data';
import UpdataRole from './components/UpdataRoles';
import {
    addAdmin,
    queryAdminDetail,
    queryAdminList,
    removeAdmin,
    updateAdminPassword,
} from './service';
import { useModel } from 'umi';

const TableList: React.FC = () => {
    const { initialState } = useModel('@@initialState');
    const currUser = initialState?.currentUser;
    // const isAdmin = currUser?.type === 1;

    const [sorter, setSorter] = useState<string>('');
    const [detailVisible, setDetailVisible] = useState<boolean>(false);
    const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
    const [clickItemId, setClickItemId] = useState<string>('');
    const [passwordVisible, setPasswordVisible] = useState<boolean>(false);
    const [clickItem, setClickItem] = useState<any>();
    const [editVisible, setEditVisible] = useState<boolean>(false);
    const [tenantId, setTenantId] = useState<string>('');

    const actionRef = useRef<ActionType>();

    const handleAdd = async (fields: AddItem) => {
        const hide = message.loading('正在添加');
        const res = await addAdmin(fields);

        hide();
        if (res.code === 0) {
            message.success(`${res.message}`);
            handleAddModalVisible(false);
            actionRef.current?.reload();
            return true;
        } else {
            message.error(res.message || '添加失败');
            return false;
        }
    };

    const handleRemove = async (fields: { id: string }) => {
        const hide = message.loading('正在删除');

        const res = await removeAdmin(fields);

        if (res.code == 0) {
            hide();
            message.success('删除成功');
            actionRef.current?.reload();
            return true;
        } else {
            hide();
            message.error(`${res.message}`);
            return false;
        }
    };

    const columns: ProColumns<TableListItem>[] = [
        {
            title: '管理员名称',
            dataIndex: 'name',
            ellipsis: true,
        },
        {
            title: '管理员账号',
            dataIndex: 'userName',
            ellipsis: true,
        },
        {
            title: '账户角色',
            dataIndex: 'roles',
            width: 380,
            hideInSearch: true,
            ellipsis: true,
            render: (_, record) => {
                return (
                    <Popover
                        placement="topLeft"
                        content={
                            <div style={{ display: 'flex' }}>
                                {record.roles?.map((item) => (
                                    <Tag style={{ marginRight: 7, fontSize: 13 }} key={item.id}>
                                        {item.name}
                                    </Tag>
                                ))}
                            </div>
                        }
                    >
                        {record.roles?.map((item) => (
                            <Tag key={item.id}>{item.name}</Tag>
                        ))}
                        {record.roles.length < record.roles.length ? '...' : ''}
                    </Popover>
                );
            },
        },
        {
            title: '更新时间',
            dataIndex: 'update_time',
            ellipsis: true,
            search: false,
            render: (_, record) => <Tag>{record.update_time}</Tag>,
        },
        {
            title: '权限管理',
            dataIndex: 'roles',
            search: false,
            ellipsis: true,
            render: (_, record) => {
                if (record.type != currUser?.type && currUser?.type ? currUser?.type <= 2 : '') {
                    return (
                        <a
                            style={{ marginRight: 20 }}
                            onClick={() => {
                                setEditVisible(true);
                                setClickItem(record);
                                setClickItemId(record.id);
                            }}
                        >
                            修改权限
                        </a>
                    );
                } else {
                    return <div style={{ color: 'grey' }}>没有权限配置</div>;
                }
            },
        },
        {
            title: '操作',
            dataIndex: 'options',
            hideInSearch: true,
            ellipsis: true,
            render: (_, record) => {
                const onClickDetail = () => {
                    setDetailVisible(true);
                    setClickItemId(record.id);
                };
                const onClickRemove = () => {
                    const { id, userName } = record;
                    Modal.confirm({
                        title: `删除管理员 ${id}`,
                        content: (
                            <>
                                <Divider />
                                <p>确认要删除管理员</p>
                                <span style={{ fontWeight: 'bolder' }}>{userName}</span>
                                &nbsp;&nbsp;?
                            </>
                        ),
                        okText: '确定',
                        cancelText: '取消',
                        onOk: async () => {
                            await handleRemove({ id });
                        },
                        centered: true,
                        width: '30vw',
                        style: { height: '15vw' },
                    });
                };
                if (record.type != currUser?.type && currUser?.type ? currUser?.type <= 2 : '') {
                    return (
                        <div>
                            <a onClick={onClickDetail}>详情</a>
                            <Divider type="vertical" />
                            <a
                                onClick={() => {
                                    setClickItemId(record.id);
                                    setPasswordVisible(true);
                                }}
                            >
                                修改密码
                            </a>
                            <Divider type="vertical" />
                            <a onClick={onClickRemove}>删除</a>
                        </div>
                    );
                } else {
                    return (
                        <div>
                            <a onClick={onClickDetail}>详情</a>
                            <Divider type="vertical" />
                            <a
                                onClick={() => {
                                    setClickItemId(record.id);
                                    setPasswordVisible(true);
                                }}
                            >
                                修改密码
                            </a>
                            <Divider type="vertical" />
                            <a style={{ color: 'gray' }}>删除</a>
                        </div>
                    );
                }
            },
        },
    ];

    return (
        <PageHeaderWrapper>
            <ProTable<TableListItem>
                pagination={{
                    defaultPageSize: 10,
                    size: 'default',
                    showQuickJumper: true,
                    showSizeChanger: true,
                }}
                search={{
                    labelWidth: 'auto',
                    span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
                }}
                headerTitle="管理员列表"
                actionRef={actionRef}
                rowKey="id"
                scroll={{ x: true }}
                onChange={(_, _filter, _sorter) => {
                    const sorterResult = _sorter as SorterResult<TableListItem>;
                    if (sorterResult.field) {
                        setSorter(`${sorterResult.field}_${sorterResult.order}`);
                    }
                }}
                params={{
                    sorter,
                }}
                toolBarRender={() => [
                    <Button key={''} type="primary" onClick={() => handleAddModalVisible(true)}>
                        <PlusOutlined /> 添加
                    </Button>,
                ]}
                tableAlertRender={() => false}
                rowSelection={false}
                request={async (params = {}) => {
                    const res = await queryAdminList(params);
                    setTenantId(res.data ? res.data[0].tenant_id : '');
                    return res;
                }}
                columns={columns}
            />
            {addModalVisible && (
                <AddFrom
                    modalVisible={addModalVisible}
                    onSubmit={(value: AddItem) => handleAdd(value)}
                    onCancel={() => handleAddModalVisible(false)}
                />
            )}
            <Drawer
                visible={!!clickItemId && detailVisible}
                onClose={() => setDetailVisible(false)}
                width="330"
            >
                {!!clickItemId && detailVisible && (
                    <AccountDetail
                        id={clickItemId}
                        tenant_id={tenantId}
                        request={(id) => queryAdminDetail({ id })}
                        reloadFunc={() => actionRef.current?.reload()}
                    />
                )}
            </Drawer>
            <Modal
                footer={null}
                visible={passwordVisible}
                centered
                title="修改密码"
                destroyOnClose
                style={{ marginBottom: 100 }}
                onCancel={() => {
                    setPasswordVisible(false);
                }}
            >
                <ProForm
                    layout="horizontal"
                    onFinish={async (value) => {
                        const values = {
                            password: value.password,
                            admin_id: clickItemId,
                        };
                        const hide = message.loading('正在修改');
                        const res = await updateAdminPassword(values);

                        hide();
                        if (res.code === 0) {
                            message.success(`${res.message}`);
                            setPasswordVisible(false);
                            actionRef.current?.reload();
                            return true;
                        } else {
                            message.error(`${res.message}`);
                            return false;
                        }
                    }}
                >
                    <Form.Item
                        name="password"
                        label="新密码"
                        rules={[{ required: true, message: '新密码不能为空' }]}
                    >
                        <Input type="password" />
                    </Form.Item>
                </ProForm>
            </Modal>
            {clickItem && editVisible && (
                <UpdataRole
                    item={clickItem}
                    modalVisible={editVisible}
                    onSubmit={() => {
                        setEditVisible(false);
                        setClickItem(undefined);
                        actionRef.current?.reload();
                    }}
                    onVisibleChange={(visible) => {
                        setEditVisible(visible);
                    }}
                />
            )}
        </PageHeaderWrapper>
    );
};

export default TableList;
